﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.Model;
using EzDesk.Core.CoreImpl.Filters;
using System.Net;
using System.Xml.Linq;

namespace EzDesk.Core.CoreImpl
{
    public partial class CoreService : ICoreService
    {

        App ICoreService.RegistApp(string appName)
        {
            throw new NotImplementedException();
        }

        void ICoreService.DeleteApp(App app)
        {
            throw new NotImplementedException();
        }

        IList<App> ICoreService.GetAllApps()
        {
            return _appRepository.GetAll()
                .ToList();
        }

        App ICoreService.GetAppByName(string appName)
        {
            var app = _appRepository.GetAll()
               .ByName(appName);
            if (app == null)
            {
                throw new Exception("App does not exist!");
            }
            return app;
        }

        App ICoreService.GetAppById(Guid appId)
        {
            return _appRepository.GetById(appId);
        }


        IList<AppTask> ICoreService.GetAllAppTasks(Guid userId, string userAgent)
        {
            List<AppTask> taskList = new List<AppTask>();
            var allApps = _appRepository.GetAll();
            foreach (var app in allApps)
            {
                IList<AppTask> tasks = self.GetAppTasksByAppName(app.Name, userId, userAgent);
                taskList.AddRange(tasks);
            }
            return taskList;
        }

        IList<AppTask> ICoreService.GetAppTasksByAppName(string appName, Guid userId, string userAgent)
        {
            try
            {
                string targetUrl = string.Format("http://{0}/task", _appPortalService.GetAppDomainName(appName, userAgent));
                string xmlString = _appPortalService.GetPortalRequests(
                    "GET",
                    targetUrl,
                    appName,
                    userId
                    ).Content;
                IList<AppTask> appTasks = generateAppTasksFromXmlString(xmlString, appName);
                return appTasks;
            }
            catch (Exception ex)
            {
                throw new Exception("App错误，找不到TaskList或Task格式错误", ex);
            }
        }



        private IList<AppTask> generateAppTasksFromXmlString(string xmlString, string appName)
        {
            IList<AppTask> appTasks = new List<AppTask>();
            XElement tasksXml = XElement.Parse(xmlString);
            var tasks = tasksXml.Elements("apptask");
            foreach (var task in tasks)
            {
                StringBuilder realUrlBuilder = new StringBuilder();
                realUrlBuilder.AppendFormat("http://{0}/page{1}", self.AppPortalUrl, task.Attribute("funcurl").Value);

                AppTask aTask = new AppTask()
                {
                    AppName = appName,
                    Title = task.Attribute("title").Value,
                    Description = task.Attribute("description").Value,
                    FuncUrl = realUrlBuilder.ToString(),
                };
                appTasks.Add(aTask);
            }
            
            return appTasks;
        }
    }
}
